package com.dataart.training.crimequalification.service;

import com.dataart.training.crimequalification.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    //-------------------------------------------------------------------------

    @Autowired
    private UserService userService;

    //-------------------------------------------------------------------------

    /**
     * Locates the user based on the username.
     *
     * @param username the username identifying the user whose data is required
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no GrantedAuthority
     * @throws DataAccessException       if user could not be found for a repository-specific reason
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

        UserEntity user;

        try {
            user = userService.getUserByUsername(username);
        } catch (Exception e) {
            throw new DataRetrievalFailureException(e.getMessage(), e);
        }

        if (user == null) {
            throw new UsernameNotFoundException("User by username " + username + " not found.");
        }

        return userService.userEntityToUserDetails(userService.getUserByUsername(username));
    }


}
